﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Model
{
    public class DownLoadTask : INotifyPropertyChanged
    {
        public DownLoadTask(Action<IProgress<double>, IProgress<TaskStatus>, CancellationToken> downloadAction)
        {
            DownloadAction = downloadAction;
            cancelsource= new CancellationTokenSource();
        }
        public event PropertyChangedEventHandler PropertyChanged;
        public string TaskId { get; set; }
        public string TaskName { get; set; }
        public TaskStatus TaskStatus { get; set; }
        public string TaskType { get; set; }
        public string TaskUrl { get; set; }
        public string TaskPath { get; set; }
        public double TaskProgress { get; set; }
        public string TaskSpeed { get; set; }
        public string TaskSummary { get; set; }
        public Action<IProgress<double>, IProgress<TaskStatus>, CancellationToken> DownloadAction { get; }

        CancellationTokenSource cancelsource;
        public async Task StartDownloadAsync()
        {
            TaskStatus = TaskStatus.Downloading;

            if (DownloadAction != null)
            {
                var progress = new Progress<double>(p =>
                {
                    TaskProgress = p;
                });
                var status = new Progress<TaskStatus>(s =>
                {
                    TaskStatus = s;
                });
                await Task.Run(() => DownloadAction(progress, status, cancelsource.Token));

                //TaskProgress = 100;
                //if(TaskStatus!=TaskStatus.Cancelled)
                //    TaskStatus =TaskStatus.Completed;
            }
        }
        public void CancelDownload()
        {
            TaskStatus= TaskStatus.Cancelled;
            cancelsource.Cancel();
        }
    }
    public enum TaskStatus
    {
        Pending,
        Completed,
        Failed,
        Downloading,
        Cancelled
    }
}
